/**
 * 主功能页面，用于设置行业 author:mengxn date:2016年8月23日3:18:42
 */
var collectList = {
    /**
     * 分页数据 pageSize 每次请求个数 pageNum 初始加载时请求页码
     *
     */
    pageSize: 10,
    pageNum: 1,
    spankey: "",
    /**
     * 下拉函数
     */
    pullDownAction: function () {
        window.sessionStorage.collect_status = 2;
        collectList.pageNum = 1;
        $("#collect_List").html("");
        // 去除已选标签样式
        $(".head-category-nav-list").each(function () {
            $("li").removeClass("select");
            $("#selectAll").addClass("select");
        });
        collectList.spankey = "";
        collectList.collect_loadData(collectList.spankey);// 加载知识
        //console.log("下拉函数执行");
    },
    /**
     * 上拉函数 collect_status为1是初始化加载时执行 2为点击关键字时执行
     */
    pullUpAction: function () {
        window.sessionStorage.collect_status = 2;
        //console.log("上拉函数执行");
        collectList.pageNum += 1;
        // 如果没点击关键件字则传空
        if (window.sessionStorage.collect_publish_key) {
            var publish_key = window.sessionStorage.collect_publish_key;
            collectList.collect_loadData(publish_key);
        } else {
            collectList.collect_loadData("");
        }
    },
    /**
     * 调用ajax取得标签和知识 pageNum当前请求页码 pageSize请求个数
     */
    collect_loadData: function (publish_key) {
        var userid = window.localStorage.userid;
        publish_key = publish_key.substring(0, publish_key.length - 1);
        var data = {
            "favorite_user": userid,
            "pageNum": collectList.pageNum,
            "pageSize": collectList.pageSize,
            "publish_key": publish_key
        };
        var url = "/favorite/App/selectfavoriteuser";
        // 加载转圈
        //common.showLoading();
        common.interfaceAjaxFunction(url, data,
            this.loadDatasuccessCallBack, true, "", false);
    },
    /**
     * 加载成功回调 data1 为返回的关键字 data 为返回列表数据
     */
    loadDatasuccessCallBack: function (res) {
        //console.log(res);
        if (res.status != 0) {
            // 收藏数目
            $("#collect_title").text("收藏");
            $("#collect_List_top").empty();
            //定义高度
            $("#collect_List_top").css("height", $(window).height() - $(".header").height());
            //给出信息提示
            common.show_error(res.message, "collect_List_top");
            // 去除转圈
            ////common.hideLoading();
        } else {
            // 收藏数目
            //$("#collect_title").text("收藏(" + res.count + ")");
            // 当count为0 则无记录
            if (res.count == 0) {
                $("#collect_List_top").empty();
                //定义高度
                $("#collect_List_top").css("height", $(window).height() - $(".header").height() - $("#collect_List_top").height());
                common.show_nodata("当前无收藏记录", "collect_List_top");
                return;
            }

            // data1为关键字  collect_status:1 进来第一次加载标签初始化
            //if (window.sessionStorage.collect_status == 1) {
            //    if (res.data1 != undefined) {
            //        $(".head-category-nav-list").empty();
            //        var keyWordLength = 0;
            //        var key_length = 0;
            //        // 拼接关键字 如果大于10条 则只显示10条
            //        if (res.data1.length > 10) {
            //            key_length = 10;
            //        } else {
            //            key_length = res.data1.length;
            //        }
            //        //默认全部选中
            //        var HtmlAll = $('<li key_span="" class="select" id="selectAll">全部</li>');
            //        $(".head-category-nav-list").append(HtmlAll);
            //        //循环真正的关键字
            //        for (var k = 0; k < key_length; k++) {
            //            var span = res.data1[k].key;
            //            // if (span.length > 6) { span = span.substring(0,
            //            // 5) +"..."; }
            //            var Html = $('<li key_span="' + res.data1[k].key + '">' + span + '</li>');
            //            $(".head-category-nav-list").append(Html);
            //            // 去得当前的字体大小
            //            var thisFontSize = parseInt($(
            //                ".head-category-nav-list li").css("font-size"));
            //            // 累加长度
            //            keyWordLength += parseInt(Html.width() + 2 * 0.3 * (thisFontSize * 2) + 5) + 2 * 0.4 * (thisFontSize * 2 + 2);
            //        }
            //        // 宽度
            //        $("#scrollerKeyWordList").width(keyWordLength > $(window).width() ? keyWordLength : $(window).width() + "px");
            //        // 横向滚动条初始化isocroll
            //        common.initIscrollBodyHorizontal("home-nav-box");// horizontal:横向滚动，默认纵向
            //    }
            //}
            // data为列表数据
            if (res.data.length > 0) {
                for (var i = 0; i < res.data.length; i++) {
                    var collect_title = res.data[i].publish_title;
                    var collect_time = res.data[i].publish_time;
                    var collect_countpk = res.data[i].countpk;
                    var pk_km_publish = res.data[i].pk_km_publish;// 列表id
                    var collect_keywords = res.data[i].publish_key
                        .split(",");
                    var attachment_count = res.data[i].attachment_count;
                    // 收藏列表html
                    var html = '<div class="product-list" pkid=' + pk_km_publish + '>' +
                        '<div class="product-list-left">' +
                        '<div class="product-list-h1">' +
                        '<div class="product-title">' + collect_title + '</div>' +

                        '</div>' +
                        '<div class="product-list-count">' +
                        '<div class="product-list-count">';

                    html +=
                        '<div class="product-time">' + collect_time + '</div>' +  //时间
                        '<div class="product-collection">' +
                        '<span class="fr" id="fr_' + pk_km_publish + '">' + collect_countpk + '</span>' + '<i class="pro-clooect-icon">' + '</i>' +
                        '</div>' +
                        '</div>' +
                        '</div>';
                    if (attachment_count > 0) {
                        html += '</div><div class="product-list-attachment"><img id="right-icon' + pk_km_publish + '" class="product-list-right-icon" src="images/wd2.png"><span class="product-list-circle">' + attachment_count + '</span></div>';
                    } else {
                        html += '</div><div class="product-list-attachment"><img id="right-icon' + pk_km_publish + '" class="product-list-right-icon" src="images/wd1.png"></div>';
                    }
                    $("#collect_List").append(html);
                }
            } else {
                if ($(".product-list").length > 0) {
                    common.showTip("已加载全部收藏信息");
                }
            }
            // 去除转圈
            ////common.hideLoading();
            // iscroll初始化
            common.initIscroll("collectListContent", collectList.pullDownAction, collectList.pullUpAction);
            // 点击事件
            collectList.bindEvent();
        }
    },
    queryAttachmentCallBack: function (res) {
        if (res.status != 0) {
            common.showTip(res.message);
        } else {
            var attachmentArray = res["data"][0].achementList_oth;
            console.log(attachmentArray);
            $("#collect-attachmentList_List").html("");
            if (attachmentArray && attachmentArray.length > 0) {
                for (var i = 0; i < attachmentArray.length; i++) {
                    var att = attachmentArray[i];
                    var fileType = att.filename.split(".").pop();
                    var imageurl = "images/";
                    switch (fileType.toLowerCase()) {
                        case "docx":
                        case "doc":
                            imageurl += "word";
                            break;
                        case "pdf":
                            imageurl += "pdf";
                            break;
                        case "xlsx":
                        case "xls":
                            imageurl += "excel";
                            break;
                        case "pptx":
                        case "ppt":
                            imageurl += "ppt";
                            break;
                        case "mp4":
                            imageurl += "mp4";
                            break;
                        default:
                            imageurl += "other";
                            break;
                    }
                    imageurl += ".png";
                    var attHtml = '<div class="attachment_item" dataurl="' + att.fileurl + '" fileName= "' + att.fname + '" fileType="' + fileType + '" pk_attachment= "' + att.pk_attachment + '" thisFileSize="' + att.filesize + '">' +
                        '<div class="attachment-icon"><img src=' + imageurl + '></div>' +
                        '<div class="attachment-content">' +
                        '<div class="attachment-title">' + att.fname + '</div>' +
                        '<div class="attachment-size">' + att.filesize + '</div>' +
                        '<div id="skill"><div><span class="expand html5" id="' + att.pk_attachment + '" style="display:none;"></span></div></div>' +
                        '</div>' +
                        '</div>';
                    $("#collect-attachmentList_List").append(attHtml);
                }
                //初始化上拉加载下拉刷新控件
                common.initIscrollBody("attachmentList_collectList_iscroll");
                $("#collect-list-attachment").show();
                collectList.initAttachmentDownload();
                //关闭
                $(".point").unbind().on("click", function () {
                    $(".mask").hide();
                });
            }
        }
    },

    initAttachmentDownload: function () {
        $(".attachment_item").unbind().on("click", function () {
            var url = $(this).attr("dataurl");
            var type = $(this).attr("fileType");
            var fileName = $(this).attr("fileName") + "." + type;
            var id = $(this).attr("pk_attachment");
            var filePath = "shellkm" + "/";
            fileName = id + "," + fileName;
            $("#" + id).addClass(id);

            var fileSize = $(this).attr("thisFileSize");

            //判断文件是否已经存在。
            var flag = $file.exists({
                path: filePath,
                file: fileName
            });

            if (flag != "false") {
                //重新记录一次
                collectList.recordCurrentUserAttachDownloadFiles(fileName, filePath, id, type, url, fileSize);
                collectList.openfile(type, filePath, fileName);
                return false;
            } else {
                url = common.contextPath() + "/file/appdownloadFile/" + id;
                collectList.downloadDocx(url, filePath, fileName);
            }
        });
    },
    /**
     * 绑定点击事件
     *
     */
    bindEvent: function () {
        // 点击列表
        $(".product-list-left").unbind().on("click", function () {
            window.sessionStorage.collect_status = 2;
            window.sessionStorage.product_detail_id = $(this).parent().attr("pkid");
            window.location.href = "#detail";
        });
        /**
         * 获取附件
         */
        $(".product-list-attachment").unbind().on("click", function () {
            var attachmentNum = $(this).children(".product-list-circle").text();
            if (attachmentNum > 0) {
                var pk_knowledge = $(this).parent().attr("pkid");
                var url = "/kmpublish/App/queryAttByPK";
                var functionParam = {
                    "pk_publish": pk_knowledge,
                    "pk_user": window.localStorage.userid
                };
                common.interfaceAjaxFunction(url, functionParam, collectList.queryAttachmentCallBack, true);
            }
        });
        // 点击标签 collect_status
        $(".head-category-nav-list li").unbind().on(
            "click",
            function (e) {
                $("#collect_List").empty();// 初始化列表
                window.sessionStorage.collect_status = 2;
                collectList.pageNum = 1;
                //当前选择的值
                var key_span_value = $(e.currentTarget).attr('key_span');
                //如果想取消全部，则直接查全部数据
                if (key_span_value == "") {
                    $(".head-category-nav-list li").removeClass("select");
                    $("#selectAll").addClass("select");
                    collectList.spankey = "";
                    collectList.collect_loadData(collectList.spankey);
                    window.sessionStorage.collect_publish_key = collectList.spankey;
                    return;
                }

                if ($(e.currentTarget).hasClass("select")) {
                    // 点击取消入参去除相应标签
                    collectList.spankey = collectList.spankey.replace(key_span_value + ",", "");
                    collectList.collect_loadData(collectList.spankey);
                    $(this).removeClass("select");
                } else {
                    // 点击标签增加相应标签
                    $("#selectAll").removeClass("select");
                    collectList.spankey += key_span_value + ",";
                    collectList.collect_loadData(collectList.spankey);
                    $(this).addClass("select");
                }
                //全部取消的时候
                if (!$(".head-category-nav-list li").hasClass("select")) {
                    $("#selectAll").addClass("select");
                }
                window.sessionStorage.collect_publish_key = collectList.spankey;
            });
    },
    /**
     * 进行页面路由监听配置，覆盖首页设置的路由
     *
     */
    bindRout: function () {
        //选择详情页面
        Path.map("#detail").to(function () {
            //session中记录一下
            window.sessionStorage.detailPageFromRout = "mine";
            //记录状态
            common.loadPageDiv("html/detail.html", true);
        });
        Path.listen();
    },
    /**
     * each page
     */
    initialize: function () {
        collectList.bindEvent();// 绑定事件
        collectList.bindRout();// 绑定路由
        collectList.pageNum = 1;
        collectList.collect_loadData("");// 加载知识
        window.sessionStorage.collect_status = 1;
        //定义页面列表高度
        //$("#collect_List").css("min-height",$(window).height() - $("#header").height() - $("#collect_List_top").height());
    },
    downloadCall: function (args) {
        var name = args.filename;
        var id = name.split(",")[0];
        $("#" + id).show();
        if (args.isfinish) {
            common.showTip("下载完成");
            $('.' + id).css('width', "70%");
            var path = args.filepath;
            type = name.split(".").pop();
            $("#" + id).removeClass(id);
            setTimeout(function () {
                $("#" + id).hide();
            }, 2000);
            //xiaz
            collectList.recordCurrentUserAttachDownloadFiles(name, args.savePath, id, type, args.url, "");
            //最后打开文件
            $file.open({
                "filename": name,//文件全路径
                "filetype": type,
                "filepath": path
            });
        } else {
            var percent = parseInt(args.percent) * 0.75;
            console.log(args.percent + ",percent===" + percent);
            $('.' + id).css('width', percent + "%");
        }
    },
    errorFunction: function (res) {
        alert(res);
    },

    openfile: function (filetype, filepath, filename) {
        $file.open({
            "filename": filename,//文件全路径
            "filetype": filetype,
            "filepath": filepath
        })
    },
    downloadDocx: function (url, filepath, filename) {
        //开始了
        var getNetworkInfo = JSON.parse($net.getNetworkInfo());
        // //判断是否为wifi连接，
        if (getNetworkInfo.Type == "Wifi" || getNetworkInfo.Type == "WiFi") {
            $file.download({
                "url": url,
                "locate": filepath,
                "filename": filename,
                "override": "true",
                "callback": "collectList.downloadCall()",
                "error": "collectList.errorFunction()"
            });
        } else {
            common.showConfirm("您未链接Wi-Fi，确定使用流量下载附件吗？", function () {
                $file.download({
                    "url": url,
                    "locate": filepath,
                    "filename": filename,
                    "override": "true",
                    "callback": "collectList.downloadCall()",
                    "error": "collectList.errorFunction()"
                });
            });

        }
    },
    //记录附件下载的公共函数
    recordCurrentUserAttachDownloadFiles: function (fileName, savePath, id, type, url, thisFileSize) {
        //当前年月日计算
        var myDate = new Date();
        //年
        var att_year = myDate.getFullYear();
        //获取当前月份
        var att_month = parseInt(myDate.getMonth()) + 1;
        //获取当前日
        var att_day = myDate.getDate();

        //文件大小
        var fileSize = 0;
        if (thisFileSize == "" || thisFileSize == undefined) {
            //下载的文件信息
            var savePathInfo = $file.getFileInfo(savePath);
            if (typeof(savePathInfo) == "string") {
                fileSize = common.strToJson(savePathInfo).size;
            } else {
                fileSize = savePathInfo.size;
            }
            fileSize = common.calcFileSize(fileSize);
        } else {
            fileSize = thisFileSize;
        }
        //保存当前信息到本地存储当中去
        var thisFileInfo = {
            "att_day": parseInt(att_day) < 10 ? "0" + att_day : att_day,
            "att_month": parseInt(att_month) < 10 ? "0" + att_month : att_month,
            "att_year": att_year,
            "filename": fileName,
            "filesize": fileSize,
            "fileurl": url,
            "fname": fileName.split(",")[1].substring(0, fileName.split(",")[1].lastIndexOf(".")),
            "pk_attachment": id,
            "pk_business": "",
            "upload_type": type
        };
        //取得当前的json串值
        var currentUserAttachDownloadFiles = common.strToJson(window.localStorage.currentUserAttachDownloadFiles);
        if (typeof(currentUserAttachDownloadFiles) == "undefined") {
            currentUserAttachDownloadFiles = [];
        }
        //从0开始
        var i = 0;
        for (i = 0; i < currentUserAttachDownloadFiles.length; i++) {
            console.log(currentUserAttachDownloadFiles[i].fname);
            if (thisFileInfo.pk_attachment == currentUserAttachDownloadFiles[i].pk_attachment) {
                console.log("已经存在");
                break;
            }
        }
        if (i == currentUserAttachDownloadFiles.length) {
            currentUserAttachDownloadFiles.push(thisFileInfo);
            //保存到本地
            window.localStorage.currentUserAttachDownloadFiles = JSON.stringify(currentUserAttachDownloadFiles);
        }
    }
};
